﻿
using Castle.Core.Internal;
using Coldairarrow.Business.Interface;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.Interface;
using Coldairarrow.Util;
using Microsoft.Extensions.Options;
using NetTopologySuite.Index.HPRtree;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Diagnostics.Tracing;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Net;
using System.Reflection.Metadata;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Coldairarrow.Business.Interface
{
    public class EC_ProductInvInterfaceBusiness : ECInterface_BaseBusiness, IJob_Business, ITransientDependency
    {
        //接口信息
        public Base_InterfaceOption EC_Query;
        public EC_ProductInvInterfaceBusiness()
        {
            this.InterfaceName = "易仓库存信息";
            //索引字段
            this.MapFields = GetMapField("EC_Query");

            //获取此接口的所有API信息
            this.interfaceOption = SqlDb.GetListBySql<Base_InterfaceOption>(@$"SELECT * FROM  Base_InterfaceOption(NOLOCK) WHERE Name='{InterfaceName}' ");
            EC_Query = this.interfaceOption.Where(x => x.OperateType == "EC_Query").First();

            //查询执行前的事件
            this.BeforeQueryEvent += InterfaceBusiness_BeforeQueryEvent;
            //查询执行中的事件
            this.OnQueryEvent += InterfaceBusiness_OnQueryEvent;
            //查询执行中的事件
            this.AfterQueryEvent += InterfaceBusiness_AfterQueryEvent;

            //执行非查询请求中的事件
            this.OnNoQueryEvent += InterfaceBusiness_OnNoQueryEvent;

        }

        /// <summary>
        /// 执行非查询请求中事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="EC_NoQueryEventArgs"></param>
        private void InterfaceBusiness_OnNoQueryEvent(object sender, EC_NoQueryEventArgs EC_NoQueryEventArgs)
        {
            //API请求是否成功
            EC_NoQueryEventArgs.Success = EC_NoQueryEventArgs.Result["success"].ToString().ToBool();
        }

        /// <summary>
        /// 查询执行前的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private async void InterfaceBusiness_BeforeQueryEvent(object sender, EC_QueryEventArgs queryEventArgs)
        {
            try
            {
                //获取请求的参数
                string pairs_s = queryEventArgs.APINodes.Where(x => x.TargetField == "biz_content").First().SreachKey;
                JObject pairs_o = JObject.Parse(pairs_s);
                queryEventArgs.CustomData = pairs_o;
                //获取
                queryEventArgs.CustomData2 = queryEventArgs.APINodes.Where(x => x.TargetField == "app_key").First().SreachKey; ;
                //设置查询第几页
                queryEventArgs.Page.PageIndex = 1;
                //一页的数量
                queryEventArgs.Page.PageSize = pairs_o["page_size"].ToString().ToInt();
            }
            catch (Exception ex)
            {

            }


        }

        /// <summary>
        /// 查询中的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_OnQueryEvent(object sender, EC_QueryEventArgs queryEventArgs)
        {
            try
            {
                //获取请求的数据
                EC_ReqDTO data = new EC_ReqDTO();
                data.timestamp = DateTime.Now.ToUnixTimeStampMillis();
                var par = (JObject)queryEventArgs.CustomData;
                par["page"] = queryEventArgs.Page.PageIndex;
                data.biz_content = par.ToJson();
                data.sign = "";
                //获取Sign
                queryEventArgs.reqData = GetJsonData(queryEventArgs.APINodes, queryEventArgs.ParentNode, data);
                var reqData = JObject.Parse(queryEventArgs.reqData);
                //获取所有json节点的信息
                var nodes = queryEventArgs.APINodes.Where(x => x.ParentNO == "TOP" && x.OptionId == EC_Query.Id);
                //需要将请求的数据拼接到url中，先转换成字典
                Dictionary<string, object> reqKeyValue = new Dictionary<string, object>();
                foreach (var item in nodes)
                {
                    if (!reqData[item.TargetField].ToString().IsNullOrEmpty())
                    {
                        reqKeyValue.Add(item.TargetField, reqData[item.TargetField].ToString());
                    }
                }
                data.sign = GetMD5Sign(reqKeyValue, queryEventArgs.CustomData2.ToString());
                queryEventArgs.reqData = GetJsonData(queryEventArgs.APINodes, queryEventArgs.ParentNode, data);
            }
            catch (Exception ex)
            {
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
            }
        }

        /// <summary>
        /// 查询执行后的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_AfterQueryEvent(object sender, EC_QueryEventArgs queryEventArgs)
        {

            try
            {
                //将查询后的数据转换成对应格式的数据
                ProInvDTO result = (ProInvDTO)JsonConvert.DeserializeObject<ProInvDTO>(queryEventArgs.ResultStr);
                if (result.message == "Success")
                {
                    ProInvDTO_Data DTO_data = (ProInvDTO_Data)JsonConvert.DeserializeObject<ProInvDTO_Data>(result.biz_content);
                    //查询数量小于单页最大数量查询完成
                    if (DTO_data.data.Count < queryEventArgs.Page.PageSize)
                    {
                        queryEventArgs.Page.Complete = true;
                    }
                    else
                    {
                        //查询下一页
                        queryEventArgs.Page.PageIndex++;
                    }
                    queryEventArgs.Rows = DTO_data.data;
                    queryEventArgs.Success = true;
                }
                else
                {
                    queryEventArgs.Success = false;
                }
                Thread.Sleep(20000);
            }
            catch (Exception ex)
            {
                queryEventArgs.Success = false;
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
                Thread.Sleep(20000);
            }

        }

        /// <summary>
        /// 执行增删改查业务
        /// </summary>
        public async void ExecuteInterface()
        {
            List<ProInv> QQ = await this.QueryAsync<ProInv>(this.EC_Query, SqlDb);
        }

        /// <summary>
        /// 获取MD5 sign
        /// </summary>
        /// <param name="url"></param>
        /// <param name="access_token"></param>
        /// <param name="app_key"></param>
        /// <param name="reqData"></param>
        /// <returns></returns>
        public string GetMD5Sign(Dictionary<string, object> reqKeyValue,string secret_Key)
        {

            reqKeyValue = reqKeyValue.OrderBy(x => x.Key).ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
            StringBuilder sb = new StringBuilder();
            foreach (var item in reqKeyValue)
            {
                sb.Append(item.Key);
                sb.Append("=");
                sb.Append(item.Value);
                sb.Append("&");
            }
            //移除左后一个&连接符号
            sb.Remove(sb.Length - 1, 1);
            sb.Append(secret_Key);
            string sign = sb.ToString().Replace("\n", "").Replace("\r", "").Replace(" ", "");
            //MD5加密
            sign = sign.ToMD5String().ToLower();
            return sign;
        }

        /// <summary>
        /// 任务
        /// </summary>
        public void Job()
        {
            ExecuteInterface();
        }
    }

}
